import paramiko
import os

# 文件分发,和SSH思路类似

def sftp_upload(host, user, key_path, local_path, remote_path):
    transport = None
    sftp = None
    try:
        transport = paramiko.Transport((host,     22))
        private_key = paramiko.RSAKey.from_private_key_file(key_path)
        transport.connect(username=user, pkey=private_key)
        sftp = paramiko.SFTPClient.from_transport(transport)
        sftp.put(local_path, remote_path)
        return {
            "status": "success",
            "host": host,
            "local_path": local_path,
            "remote_path": remote_path,
            "message": f"File uploaded successfully from {local_path} to {remote_path}"
        }

    except Exception as e:
        return {
            "status": "error",
            "host": host,
            "local_path": local_path,
            "remote_path": remote_path,
            "message": str(e)
        }
    finally:
        # 确保关闭连接
        if sftp:
            sftp.close()
        if transport:
            transport.close()